package com.kb.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kb.erp.domain.other.CrmWaitInvoiceData;
import com.kb.erp.domain.other.CrmWaitInvoiceDetails;
import com.kb.erp.domain.other.InvoiceSearchDTO;
import com.kb.erp.entity.crm.CrmDocumentEntity;
import com.kb.erp.entity.crm.Invoice;
import com.kb.erp.mapper.pg.CrmToK3Mapper;
import com.kb.erp.service.K3Service;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static net.sf.jsqlparser.parser.feature.Feature.update;

@DS("SmartQuote_kb_live")
@Service
public class K3ServiceImpl implements K3Service {

    @Resource
    private CrmToK3Mapper mapper;

    @Override
    public List<CrmWaitInvoiceData> queryWaitInvoiceList(InvoiceSearchDTO invoiceSearchDTO) {
        //查询待开票列表数据
        LambdaQueryWrapper<Invoice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Invoice::getStatus, "Confirmed");
        // 设置时间范围：如果为空，默认查询今年的数据
        LocalDate startDate = invoiceSearchDTO.getStartDate();
        LocalDate endDate = invoiceSearchDTO.getEndDate();

        if (startDate == null || endDate == null) {
            // 获取当前年份
            LocalDate now = LocalDate.now();
            int currentYear = now.getYear();
            startDate = LocalDate.of(currentYear, 1, 1);  // 今年第一天
            endDate = LocalDate.of(currentYear, 12, 31);  // 今年最后一天
        }

        queryWrapper.between(Invoice::getInvoiceDate, startDate, endDate);
        queryWrapper.eq(StringUtils.isNotBlank(invoiceSearchDTO.getCustCode()), Invoice::getCustCode, invoiceSearchDTO.getCustCode());
        queryWrapper.eq(StringUtils.isNotBlank(invoiceSearchDTO.getInvoiceNumber()), Invoice::getInvoiceNumber, invoiceSearchDTO.getInvoiceNumber());
        List<Invoice> invoices = mapper.selectList(queryWrapper);

        if (CollectionUtils.isNotEmpty(invoices)) {
            List<CrmWaitInvoiceData> crmWaitInvoiceData = BeanUtil.copyToList(invoices, CrmWaitInvoiceData.class);
            for (CrmWaitInvoiceData crmWaitInvoiceDatum : crmWaitInvoiceData) {
                List<CrmWaitInvoiceDetails> crmWaitInvoiceDetails = mapper.queryWaitInvoiceList(crmWaitInvoiceDatum.getRecId());
                if (CollectionUtils.isNotEmpty(crmWaitInvoiceDetails) && StringUtils.isNotBlank(crmWaitInvoiceDetails.get(0).getTradeRouteDesc())) {
                    crmWaitInvoiceDatum.setTradeRouteDesc(crmWaitInvoiceDetails.get(0).getTradeRouteDesc());
                }
                crmWaitInvoiceDatum.setDetails(crmWaitInvoiceDetails);
            }
            return crmWaitInvoiceData;
        }
        return List.of();
    }

    @Override
    public CrmDocumentEntity queryDocument(String fileId) {
        return mapper.queryDocument(fileId);
    }

    @Override
    public boolean updateInvoiceInfo(Invoice invoice) {
        String taxInvoiceNo = invoice.getTaxInvoiceNo();
        if (StringUtils.isBlank(taxInvoiceNo)){
            throw new RuntimeException("发票编号不能为空");
        }
        //先查询该发票是否有值，有则拼接更新，无则插入
        Invoice queryInvoice = mapper.queryInvoiceByInvoiceNumber(invoice.getInvoiceNumber());
        if (queryInvoice == null){
            throw new RuntimeException("此发票已不存在，请联系管理员");
        }
        if (StringUtils.isNotBlank(queryInvoice.getTaxInvoiceNo())){
            invoice.setTaxInvoiceNo(queryInvoice.getTaxInvoiceNo()+ "," + taxInvoiceNo);
        }
        UpdateWrapper<Invoice> update = new UpdateWrapper<>();
        update.eq("InvoiceNumber", invoice.getInvoiceNumber());
        invoice.setStatus("Invoice");
        invoice.setBillingNotes("k3开票同步: "+ DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
        return mapper.update(invoice, update) > 0;
    }
}
